package org.jwos.platform.desktop.login.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.jwos.platform.desktop.web.BaseActionSupport;
import org.jwos.platform.domain.User;
import org.jwos.platform.service.SessionManager;
import org.jwos.platform.service.UserManager;

public class LoginAction extends BaseActionSupport implements ServletRequestAware {
	
	private String username;
	
	private String password;
	
	private String language;
	
	private UserManager userManager;
	
	private SessionManager sessionManager;
	
	private HttpServletRequest request;
	
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public void setSessionManager(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}
	
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

    public String execute() throws Exception {

        if (isInvalid(getUsername())) return INPUT;

        if (isInvalid(getPassword())) return INPUT;
        
        User user = this.userManager.queryUserByUserId(getUsername());
        if(user!=null && user.getPassword().equals(getPassword())) {
        	user.setLocale(language);
        	this.userManager.saveUser(user);
        	this.request.getSession().setAttribute("user", user);
        	this.sessionManager.registerSession(this.request.getSession().getId(), user);
        	return SUCCESS;
        } else {
        	return INPUT;
        }        
    }

    private boolean isInvalid(String value) {
        return (value == null || value.length() == 0);
    }    

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }    

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

	public String getLanguage() {
		return language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}	
}